package cn.itcast.crm.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.itcast.crm.eum.ErrCode;
import cn.itcast.crm.eum.SuccCode;
import cn.itcast.crm.po.User;
import cn.itcast.crm.utils.CacheUtils;

@Controller
@RequestMapping("/userRegist")
public class UserRegistController {
	private static final Logger log = Logger.getLogger(UserRegistController.class);
//    @Resource
//    @Resource xxxx
//    private SysUserService sysUserService;
    @RequestMapping("/regist")
    @ResponseBody
    public String regist(Model model,HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    	// 获取前端参数用户名称，用户密码
    	String userName = request.getParameter("userName");
    	String password = request.getParameter("password");
    	//参数不为空判断
    	if(StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) {
    		model.addAttribute(ErrCode.ParaVal_Null_Err.getValue(),ErrCode.ParaVal_Null_Err.getDesc());
    		log.debug(ErrCode.ParaVal_Null_Err.getDesc());
    		return ErrCode.ParaVal_Null_Err.getValue();
    	}
    	//获取缓存类
    	CacheUtils cacheUtils = CacheUtils.getCacheUtils();
    	List<User> userList = cacheUtils.get("userList");
    	//循环用户信息，比较用户名是否已经注册过
    	for (User u : userList) {
    		if(userName.equals(u.getUserName())) {
    			model.addAttribute(ErrCode.UName_Regist_Yes_Err.getValue(),ErrCode.UName_Regist_Yes_Err.getDesc());
    			log.debug("已经注册过了");
    			return ErrCode.UName_Regist_Yes_Err.getValue();
    		}
		}
    	userList.add(new User(userName,password,null));
    	log.debug("注册成功");
    	model.addAttribute(SuccCode.SUCCCODE.getValue(),SuccCode.SUCCCODE.getDesc());
    	return SuccCode.SUCCCODE.getValue();
    }
}